package org.springframework.study.test;

class MyCircularQueue {

	private int[] elements;      // 存储数据
	private int head;            // 头
	private int tail;            // 尾
	private int size;            // 当前元素数量
	private int length;          // 数组长度


	public MyCircularQueue(int k) {
		elements = new int[k];
		head = -1;
		tail = -1;
		size = 0;
		length = k;
	}

	public boolean enQueue(int value) {
		if (length == 0 || length == size) {
			return false;
		}
		if ((tail + 1) < length) {
			if (head == -1) {
				head++;
			}
			elements[++tail] = value;
		} else {
			tail = 0;
			elements[tail] = value;
		}
		size++;
		return true;
	}

	public boolean deQueue() {
		if (head == -1 || size == 0) {
			return false;
		}
		if (head == tail) {
			head = tail = -1;
			size = 0;
			return true;
		}
		if (head < tail) {
			head++;
			size--;
			return true;
		} else if (head > tail) {
			if ((head + 1) < length) {
				head = 0;
				size--;
				return true;
			} else {
				head++;
				size--;
				return true;
			}
		}
		return true;
	}

	public int Front() {
		if (isEmpty()) {
			return -1;
		}
		return elements[head];
	}

	public int Rear() {
		if (isEmpty()) {
			return -1;
		}
		return elements[tail];
	}

	public boolean isEmpty() {
		return size == 0;
	}

	public boolean isFull() {
		if (length == 0 || length == size) {
			return true;
		}
		return false;
	}

	public static void main(String[] args) {
		// ["MyCircularQueue","enQueue","enQueue","enQueue","enQueue","Rear","isFull","deQueue","enQueue","Rear"]
		// [[3],[1],[2],[3],[4],[],[],[],[4],[]]
		MyCircularQueue circularQueue = new MyCircularQueue(3); // 设置长度为 3
		circularQueue.enQueue(1);  // 返回 true
		circularQueue.enQueue(2); // 返回 true
		circularQueue.enQueue(3); // 返回 true
		circularQueue.enQueue(4); // 返回 false，队列已满
		circularQueue.Rear(); // 返回 3
		circularQueue.isFull(); // 返回 true
		circularQueue.deQueue(); // 返回 true
		circularQueue.enQueue(4); // 返回 true
		circularQueue.Rear(); // 返回 4
	}
}